﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Windows.Forms;
using System.Data;
using SharpMap.Layers;
using Txt2Shp4Sharp.landm;
using SharpMap.Data.Providers;


namespace Txt2Shp4Sharp.lib
{
    /// <summary>
    /// 插件开发-全局应用实例
    /// </summary>
    public class GlobalApplication: IGlobalApplication
    {
        //单例模式
        private static GlobalApplication m_instance = new GlobalApplication();
        public static GlobalApplication getInstance(){
            if (m_instance == null){
                m_instance = new GlobalApplication();
            }
            return m_instance;
        }

        //构造函数
        private GlobalApplication() { 
        }

        private Boolean m_applicationInitState = false;//全局实例的初始化状态
        private Dictionary<String,Dictionary<String, String>> m_FieldsMappings = null;
        private SharpMap.Map _gismap = null;

        private string _caption;
        private string _currentTool;
       
        private DataSet _mainDataSet;
        private string _name = "";
        private Form _mainPlatform;
        private XmlFiles _sysConfigXml;
        private string _statusStr;
        private bool _visible;

        #region 属性字段

        /// <summary>
        /// 主程序名称
        /// </summary>
        public string Name
        {
            get
            {
                this._name = this._mainPlatform.Name;
                return this._name;
            }
            set
            {
                this._name= value;
            }
        }

        /// <summary>
        /// 主程序标题
        /// </summary>
        public string Caption
        {
            get 
            {
                this._caption = this.MainPlatform.Text;
                return this._caption; 
            }
            set 
            { 
                this._caption = value;
                this._mainPlatform.Text = this._caption;
            }
        }

        /// <summary>
        /// 主程序当前使用的工具tool名称
        /// </summary>
        public string CurrentTool
        {
            get { return this._currentTool; }
            set { this._currentTool = value; }
        }

        public SharpMap.Map GisMap
        {
            get { return this._gismap; }
            set { this._gismap = value; }
        }
        /// <summary>
        /// 主程序存储GIS数据的数据集
        /// </summary>
        public DataSet MainDataSet
        {
            get { return this._mainDataSet; }
            set { this._mainDataSet = value; }
        }

       

        /// <summary>
        /// 主程序的窗体对象
        /// </summary>
        public System.Windows.Forms.Form MainPlatform
        {
            get { return this._mainPlatform; }
            set { this._mainPlatform = value; }
        }

        /// <summary>
        /// 系统配置方案
        /// </summary>
        public XmlFiles SysConfigXml
        {
            get { return this._sysConfigXml; }
            set { this._sysConfigXml = value; }
        }

        /// <summary>
        /// 主程序窗体中的状态栏
        /// </summary>
        public string StatusStr
        {
            get { return this._statusStr; }
            set
            {
                this._statusStr = value;
            }
        }

        /// <summary>
        /// 主窗体UI界面的Visible属性
        /// </summary>
        public bool Visible
        {
            get
            {
                this._visible = this.MainPlatform.Visible;
                return this._visible;
            }
            set
            {
                this._visible = value;
                this._mainPlatform.Visible = this._visible;
            }
        }

        /// <summary>
        /// 图层字段映射的所有集合
        /// </summary>
        public Dictionary<String, Dictionary<String, String>> FieldsMappings
        {
            get { return this.m_FieldsMappings; }
            set { this.m_FieldsMappings = value; }
        }


        #endregion

        #region 公共方法
        /// <summary>
        /// 初始化操作
        /// </summary>
        public void init() {
            if (this.m_applicationInitState == false)
            {
                //1.图层字段映射
                this.m_FieldsMappings = new Dictionary<String, Dictionary<string, string>>();


                //2.加载配置文件,很容易出错的地方
                string appRoot = System.Windows.Forms.Application.StartupPath;
                XmlFiles fieldsMappingXml = null;
                try
                {
                    //string appRoot = @"D:\workspace\LandTJAddin\LandTJAddin";
                    string xmlFilePath = appRoot + "\\FieldsConfig.xml";
                    if (!File.Exists(xmlFilePath))
                    {
                        return;
                    }
                    fieldsMappingXml = new XmlFiles(xmlFilePath);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    MessageBox.Show(ex.Message);
                    return;
                }

                //3.加载字段映射的配置文件
                if (fieldsMappingXml != null)
                {
                    this.initFieldsMapping(fieldsMappingXml);
                }
                else
                {
                    //
                }

                this.m_applicationInitState = true;
            }
        }

        public void fillComboBoxWithAllLayer(ComboBox layersComboBox)
        {
            
        }

        /// <summary>
        /// 获取所有图层名称集合List
        /// </summary>
        /// <returns></returns>
        public List<string> getAllMapLayerNames()
        {
            List<string> layerNames = new List<string>();
            LayerCollection layers = this._gismap.Layers;
            foreach (ILayer layer in layers)
            {
                String layerName = layer.LayerName;
                layerNames.Add(layerName);
            }

            return layerNames;
        }
       
        public int findIndexByFieldName(string layerName, string fieldName)
        {
            int fieldIndex = -1;
    

            return fieldIndex;
        }
        public List<String> findAllFieldName(string layerName)
        {
            List<String> fieldNames = new List<string>();
            ILayer pLayer = this._gismap.GetLayerByName(layerName);
            if (pLayer != null && pLayer is VectorLayer)
            {
                VectorLayer layer = (VectorLayer)pLayer;
                ShapeFile shapeFile = (ShapeFile)layer.DataSource;
                // 获取字段列表
                //var fields = shapeFile.DataProvider.Fields;
            }

            return fieldNames;
        }

        /// <summary>
        /// 获取根据图层名称document中的地图图层，目前只返回了要素图层
        /// </summary>
        /// <param name="application"></param>
        /// <param name="layerName"></param>
        /// <returns></returns>
        public VectorLayer getLayerByName(string layerName)
        {
            VectorLayer layer = null;
            ILayer pLayer = this._gismap.GetLayerByName(layerName);
            if (pLayer != null && pLayer is VectorLayer) {
                layer = (VectorLayer)pLayer;
            }
            return layer;
        }

        public void addLayerByPath(String shpfile){
            if (String.IsNullOrEmpty(shpfile) || !File.Exists(shpfile))
            {
                return;
            }
            String shpPath = System.IO.Path.GetDirectoryName(shpfile);
            String shpName = System.IO.Path.GetFileNameWithoutExtension(shpfile);
           
        }



        /// <summary>
        /// 重置图层列表中字段到目标字段选择的combobox中
        /// </summary>
        /// <param name="targetlayer"></param>
        /// <param name="fieldsComboBox"></param>
        public void resetFieldList(VectorLayer targetlayer, ComboBox fieldsComboBox)
        {
            if (targetlayer != null)
            {
                
            }
        }

        /// <summary>
        /// 定位缩放到图斑要素中
        /// </summary>
        /// <param name="layerName">目标图层的名称</param>
        /// <param name="fieldName">关联字段</param>
        /// <param name="tbId">关联字段的值-图斑ID</param>
        public void zoom2Feature(string layerName, string fieldName, string tbId)
        {
            VectorLayer targetLayer = this.getLayerByName(layerName);
            if (targetLayer != null)
            {
                string sqlStr = string.Format("{0} = '{1}'",fieldName,tbId) ;

            }  
        }

        /// <summary>
        /// 绘制举证坐标点
        /// </summary>
        /// <param name="longtide">经度</param>
        /// <param name="latitude">纬度</param>
        /// <param name="psjd"></param>
        public void graphicJZCoord( double longtide, double latitude,double psjd)
        {
            
        }

        public void graphicJZCoordWithArrow(double psd_x, double psd_y, double psjd, JzdPoint tbCenterPoint)
        {
            
        }

       
        
        #endregion

        #region  私有方法

        private void initFieldsMapping(XmlFiles xmlfile)
        {
            //FieldMapping配置信息
            XmlNodeList layerLists = xmlfile.GetNodeList("layers");
            for (int i = 0; i < layerLists.Count; i++)
            {
                XmlNode layerXmlNode = layerLists.Item(i);
                string layerId = layerXmlNode.Attributes["id"].Value.Trim();
                string layerName = layerXmlNode.Attributes["layerName"].Value.Trim();
                string desc = layerXmlNode.Attributes["desc"].Value.Trim();
                Dictionary<string, string> fieldsMappingDic = new Dictionary<string, string>();

                if (layerId == "ystdcb")
                {
                    //原始土地储备
                    string pzwhFieldName = layerXmlNode.SelectSingleNode("pzwh").InnerText;
                    string pzsjFieldName = layerXmlNode.SelectSingleNode("pzsj").InnerText;
                    string ssjdFieldName = layerXmlNode.SelectSingleNode("ssjd").InnerText;
                    string cbmjFieldName = layerXmlNode.SelectSingleNode("cbmj").InnerText;

                    fieldsMappingDic.Add("ystdcb_layerName", layerName);
                    fieldsMappingDic.Add("ystdcb_desc", desc);
                    fieldsMappingDic.Add("pzwh", pzwhFieldName);
                    fieldsMappingDic.Add("pzsj", pzsjFieldName);
                    fieldsMappingDic.Add("ssjd", ssjdFieldName);
                    fieldsMappingDic.Add("cbmj", cbmjFieldName);

                    Console.WriteLine("{0}--{1}--{2}", layerName, desc, pzwhFieldName);
                }
                else if (layerId == "cltdcb")
                {
                    //原始土地储备
                    string pzwhFieldName = layerXmlNode.SelectSingleNode("pzwh").InnerText;
                    string pzsjFieldName = layerXmlNode.SelectSingleNode("pzsj").InnerText;
                    string ssjdFieldName = layerXmlNode.SelectSingleNode("ssjd").InnerText;
                    string cbmjFieldName = layerXmlNode.SelectSingleNode("cbmj").InnerText;

                    fieldsMappingDic.Add("cltdcb_layerName", layerName);
                    fieldsMappingDic.Add("cltdcb_desc", desc);
                    fieldsMappingDic.Add("pzwh", pzwhFieldName);
                    fieldsMappingDic.Add("pzsj", pzsjFieldName);
                    fieldsMappingDic.Add("ssjd", ssjdFieldName);
                    fieldsMappingDic.Add("cbmj", cbmjFieldName);

                    Console.WriteLine("{0}--{1}--{2}", layerName, desc, pzwhFieldName);
                }
                else if (layerId == "tdgy")
                {
                    //土地供应
                    string pzwhFieldName = layerXmlNode.SelectSingleNode("pzwh").InnerText;
                    string pzsjFieldName = layerXmlNode.SelectSingleNode("pzsj").InnerText;
                    string dkytFieldName = layerXmlNode.SelectSingleNode("dkyt").InnerText;
                    string ssjdFieldName = layerXmlNode.SelectSingleNode("ssjd").InnerText;
                    string gyfsFieldName = layerXmlNode.SelectSingleNode("gyfs").InnerText;
                    string gymjFieldName = layerXmlNode.SelectSingleNode("gymj").InnerText;

                    fieldsMappingDic.Add("tdgy_layerName", layerName);
                    fieldsMappingDic.Add("tdgy_desc", desc);
                    fieldsMappingDic.Add("pzwh", pzwhFieldName);
                    fieldsMappingDic.Add("pzsj", pzsjFieldName);
                    fieldsMappingDic.Add("dkyt", dkytFieldName);
                    fieldsMappingDic.Add("ssjd", ssjdFieldName);
                    fieldsMappingDic.Add("gyfs", gyfsFieldName);
                    fieldsMappingDic.Add("gymj", gymjFieldName);

                    Console.WriteLine("{0}--{1}--{2}", layerName, desc, pzwhFieldName);
                }
                else if (layerId == "jsydgzq")
                {          
                    //建设用地管制区
                    string gzqlxdmFieldName = layerXmlNode.SelectSingleNode("gzqlxdm").InnerText;
                    string gzqmjFieldName = layerXmlNode.SelectSingleNode("gzqmj").InnerText;
                    fieldsMappingDic.Add("jsydgzq_layerName", layerName);
                    fieldsMappingDic.Add("gzqlxdm", gzqlxdmFieldName);
                    fieldsMappingDic.Add("gzqmj", gzqmjFieldName);

                    Console.WriteLine("{0}--{1}--{2}", layerName, desc, gzqlxdmFieldName);
                }
                else if (layerId == "cskzxgh")
                {
                    //城市控制性规划
                    string ghytFieldName = layerXmlNode.SelectSingleNode("ghyt").InnerText;
                    string ghytmjFieldName = layerXmlNode.SelectSingleNode("ghytmj").InnerText;
                    fieldsMappingDic.Add("cskzxgh_layerName", layerName);
                    fieldsMappingDic.Add("ghyt", ghytFieldName);
                    fieldsMappingDic.Add("ghytmj", ghytmjFieldName);

                    Console.WriteLine("{0}--{1}--{2}", layerName, desc, ghytFieldName);
                }

                //添加图层的字段配置字典
                m_instance.FieldsMappings.Add(layerId, fieldsMappingDic);
            }
        }

        #endregion
    
    }
}
